AlarmGrid = {};

AlarmGrid.sound = true;//报警声音默认打开
AlarmGrid.popup = true;//弹窗默认打开
AlarmGrid.refreshInterval = 10;
AlarmGrid.displayTime = null;
AlarmGrid.autoRefresh = false;
AlarmGrid.popNum = 0;
AlarmGrid.showVehicleOnMap = false;
AlarmGrid.maxPopupNum = 20;//最多弹窗的报警条数，超过后，前面的要清除避免占用内存

AlarmGrid.create = function () {
	$('#alarmWindow').window('close');//初始化时，隐藏报警弹屏窗口

/*	$.post(path + "/alarmConfig/listAlarmConfig", function (data) {
		$("#alarmType").append("<option value=''>请选择</option>");
		$.each(data, function (i, item) {
			$("#alarmType").append("<option value='" + item.alarmType + "'>" + item.name + "</option>");//新增
		});
	});


	this.alarmDataGrid = $("#alarmDataGrid");
	var url = path + "/alarm/dataListForMain";
	this.alarmDataGrid.datagrid({
		columns: [[
			{field: 'dvcId', hidden: true},
			{title: '显示名称', field: 'equipName', width: 80, sortable: false},
			{title: '设备号', field: 'simNo', width: 80, minWidth: 80},
			{title: '所属分组', field: 'depName', width: 120, minWidth: 80},
			//{ title: '颜色', field: 'plateColor', width: 60,minWidth:60 },
			{title: '报警类型', field: 'alarmType', width: 100},
			{
				title: '报警来源', field: 'alarmSource', width: 70, minWidth: 80,
				formatter: function (value, rowData, rowIndex) {
					if (value == "terminal") {
						return "终端报警";
					} else if (value == "platform") {
						return "平台报警";
					} else {
						return "";
					}
				}
			},
			{title: '报警时间', field: 'alarmTime', width: 120, minWidth: 100},
			/!*			{title: '经度', field: 'longitude', width: 120},
			 {title: '纬度', field: 'latitude', width: 120},*!/
			/!*{title: '报警地点', field: 'location', width: 300, minWidth: 300},*!/
			{
				title: '处理状态',
				field: 'processed',
				width: 80,
				minWidth: 80,
				formatter: function (value, rowData, rowIndex) {
					if (value == 0) {
						return "未处理";
					} else {
						return "已处理";
					}
				}
			},
			//{ title: 'id', field: 'id', width: 60,minWidth:60 }
		]],
		//height: 165,
		url: url,
		method: 'POST',
		fit: true,
		toolbar: "#alarmGridToolbar",
		//queryParams: {'queryId': 'selectProcessedAlarms'},
		idField: 'id',
		striped: true,
		loadMsg: '',
		fitColumns: true,
		singleSelect: true,
		rownumbers: true,
		pagination: true,
		nowrap: true,
		pageSize: 20,
		onDblClickRow: this.onDblClickRow,
		pageList: [20, 50, 100, 200],
		showFooter: true,
		/!*	onClickRow: function (rowIndex, rowData) {
		 me.onClickRow(rowIndex, rowData);
		 }*!/
	});*/
	//this.refreshInterval = 10;
	this.timerName = "alarmTimer";
	var strInterval = this.refreshInterval + 's';
	var me = this;

	$('body').everyTime(strInterval, this.timerName, function () {
		//do something...

		me.refreshNewAlarm();//更新模式
	});

	// var basicDataUrl = globalConfig.webPath + "/data/basicData.action";
	//var comboboxId = "alarmType";
	//Utility.easyCombobox(comboboxId, {category: "AlarmType"});
	//comboboxId = "alarmSrc";
	//Utility.easyCombobox(comboboxId, {category: "AlarmSource"});

/*	$("#muteAlarmSound").click(function () {
		var checked = $(this).attr("checked") == "checked";
		AlarmGrid.sound = checked != true;
		AlarmSound.enable(AlarmGrid.sound);
	});
	$("#disableAlarmWindow").click(function () {
		var checked = $(this).attr("checked") == "checked";
		AlarmGrid.popup = checked != true;
	});
	$("#autoRefreshAlarmGrid").click(function () {
		var checked = $(this).prop("checked");
		me.autoRefresh = checked;
		if (checked) {
			me.alarmDataGrid.datagrid('load', me.params);
		}
	});


	$("#btnQueryAlarmData").click(function () {
		var simNo = $("#alarmSimNo").val();
		var alarmType = $('#alarmType').val();
		var alarmSrc = $("#alarmSrc").val();
		var equipName = $("#equipName").val();
		me.params = {equipName: equipName, simNo: simNo, alarmType: alarmType, alarmSource: alarmSrc};

		me.alarmDataGrid.datagrid('load', me.params);
	});*/

	/*	$("#btnResetAlarm").click(function () {
	 $("#alarmSimNo").val('');
	 $('#alarmType').combobox('setValue', '');
	 $("#alarmSrc").combobox('setValue', '');
	 me.params = {queryId: "selectProcessedAlarms"};

	 me.alarmDataGrid.datagrid('load', me.params);
	 });*/


	//return alarmDataGrid;
}
//双击表格，弹出报警处理窗口，提请用户处理报警
AlarmGrid.onDblClickRow = function (rowIndex, rowData) {
	var alarmId = rowData.id;
	var date = rowData.alarmTime;
	var url = path + "/alarm/viewAlarm?alarmId=" + alarmId + "&createDate=" + date;
	InfoWindow.open(url, 400, 320, "报警处理");
}

//点击数据表格的行时，显示地图设备
AlarmGrid.onClickRow = function (rowIndex, rowData) {
	var dvcId = rowData.dvcId;
	MyMap.showVehicleOnMap(dvcId);
}


AlarmGrid.onCheckDevice = function (simNo) {
	var zTree = $.fn.zTree.getZTreeObj("deviceTree");
	var node = zTree.getNodeByParam("simNo", simNo);
	var deviceId = node.id.substring(1, node.id.length);
	zTree.checkNode(node, true, true);//指定选中ID的节点
	var ztree1 = $.fn.zTree.getZTreeObj("deviceTree"), nodes = ztree1.getCheckedNodes(true);
	var selectDeviceIds = "";
	if (nodes && nodes.length) {
		for (var i = 0, len = nodes.length; i < len; i++) {
			var node = nodes[i];
			if (typeof (node.children) == "undefined" && node.id.indexOf("v") == 0) {
				nodeId = node.id.substring(1, node.id.length)
				selectDeviceIds += nodeId + ",";
			}
		}
		if (selectDeviceIds != "") {
			selectDeviceIds = selectDeviceIds.substring(0, selectDeviceIds.length - 1);
		}

		selectDeviceIds = selectDeviceIds;
		RealDataGrid.selectDeviceIds = selectDeviceIds;
	}
	var url = path + "/realData/registerDevicesBatch";
	var params = {registerDeviceIds: selectDeviceIds};
	$.ajax({
		type: "POST",
		url: url,
		data: params,
		error: function () {
			//alert("网络连接错误，无法读取数据!");
			//Utility.done();
		},
		success: function (data) {
			//刷新实时表格数据
			RealDataGrid.refresh(false);
		}
	});
	MyMap.showVehicleOnMap(deviceId);
}


//添加报警数据
AlarmGrid.addNewAlarm = function (alarmData) {
	//此处需要判断表格的行数，如果超过100行，要全部情况
//			if(alarmData.platformState)
//			{
//				//更新809政府平台的主连接和从连接的状态
//				var ps = alarmData.platformState;
//				var src = globalConfig.webPath + "/image/no.png";
//				if(ps.MainLinkState == "已建立连接" || ps.MainLinkState == "连接成功")
//				{
//					src =  globalConfig.webPath + "/image/ok.png";
//				}
//				$("#mainLinkState").attr("src",src);
//                src = globalConfig.webPath + "/image/no.png";
//				if(ps.SubLinkState == "已建立连接" || ps.SubLinkState == "连接成功")
//				{
//					src =  globalConfig.webPath + "/image/ok.png";
//				}
//				$("#subLinkState").attr("src",src);
//				//Ext.getCmp("lbl_mainLinkState").setText(ps.mainLinkState);
//				//Ext.getCmp("lbl_subLinkState").setText( ps.subLinkState);
//			}
	//最新的报警数据列表，数组
	var me = this;
	var soundEnabled = false;
	var needPopup = false;
	if (alarmData.alarm && alarmData.alarm.length > 0) {
	/*	if (me.autoRefresh)
			me.alarmDataGrid.datagrid('load', me.params);*/
		//var alarmStore = Ext.data.StoreManager.lookup('s_alarmStore');
		var alarmArray = alarmData.alarm;
		$.each(alarmArray, function (i, alarm) {
			if (alarm.alarmType == "GpsOnline") {
				//mytree.setOnline(alarm.vehicleId, true);
			}
			else if (alarm.alarmType == "GpsOffline") {
				//mytree.setOnline(alarm.vehicleId, false);
			}
			//var rowCount = me.alarmDataGrid.datagrid("getRows").length;
			//超过最大行数，将清空表格
			//if(rowCount > 50)
			//me.alarmDataGrid.datagrid("loadData",[]);
			//me.alarmDataGrid.datagrid("insertRow",{index:0,row:alarm});
			if (alarm.popupEnabled) {
				me.updateNotify(alarm); //弹出报警窗口
				needPopup = true;
			}
			//是否弹出报警声音,后台报警设置菜单中配置某一报警类型是否有声音
			if (alarm.soundEnabled)
				soundEnabled = true;
		});

		var lastAlarm = alarmArray[alarmArray.length - 1];
		if (me.showVehicleOnMap) {
			MyMap.showVehicleOnMap(lastAlarm.vehicleId); //调用main.jsp的jS方法,显示车辆在地图中心
		}
		if (soundEnabled)
			AlarmSound.play();//报警声音打开
	}

	//如果接收到,就弹窗
	if (needPopup)
		me.popNotifyWindow();//弹出窗口

}


AlarmGrid.refreshNewAlarm = function () {
	var url = path + "/alarm/alarm";
	var me = this;
	var params = {};
	$.ajax({
		type: "POST",
		url: url,
		data: params,
		error: function () {

		},
		success: function (data) {
			var result = data;
			if (result.success) {

				if (me.popNum > me.maxPopupNum) {
					me.closeWindow();//累计条数超过限制，清空避免占用内存
				}


				me.addNewAlarm(result.data);
				//延时关闭窗口
				if (me.displayTime) {
					var now = new Date();
					var interval = now - me.displayTime;
					interval = 0.001 * interval;
					if (interval > 20) {
						me.closeWindow();
					}
				}

			} else {
				window.location = path + '/logout';
			}
		}
	});
}

var notifyWindow;
AlarmGrid.updateNotify = function (alarm) {
	this.popNum += 1;
	var alarmContent = alarm.alarmTime + ':  [<a href="#" onclick="AlarmGrid.onCheckDevice(\'' + alarm.simNo +
		'\')">' + alarm.equipName + ']<span class="' + alarm.alarmType + '" style=\'color:red\'>' + alarm.alarmTypeDescr + '</span></a>';
	alarmContent += "<br/>";
	$("#alarmBox").prepend(alarmContent);
}
AlarmGrid.closeWindow = function () {
	this.popNum = 0;
	this.clearWindow();
	$('#alarmWindow').window('close');
}


AlarmGrid.popNotifyWindow = function (alarm) {
	//如果禁止弹窗，则直接返回，不再打开窗口
	if (AlarmGrid.popup == false)
		return;
	if (notifyWindow == null) {
		notifyWindow = $('#alarmWindow').window({
			title: '报警消息',
			width: 320,
			height: 200,
			top: ($(window).height() - 200),
			left: ($(window).width() - 320),
			shadow: false,
			modal: false,
			iconCls: 'fa fa-warning',
			closed: true,
			minimizable: false,
			maximizable: false,
			collapsible: false
		});
	}

	$('#alarmWindow').window('open');
	this.displayTime = new Date();//更新窗口的显示时间，便于延迟加载
	//var alarmContent = alarm.alarmTypeDescr;//tpl.applyTemplate(alarm);
//notifyWindow.update(alarmContent); //根据数据，填充模板，再更新到窗口上
	//console.log(alarmContent);
	//notifyWindow.show();
	if (alarm)
		this.updateNotify(alarm);

}

//清除报警窗口中的内容
AlarmGrid.clearWindow = function () {
	$("#alarmBox").empty();
	this.popNum = 0;
}

	

